package com.lean.android.ad.core.feed

import android.app.Activity
import androidx.annotation.RestrictTo
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdNative.FeedAdListener
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTFeedAd
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot
import com.lean.android.ad.core.AdLoadState
import com.lean.android.ad.core.AdLoader
import com.lean.android.ad.core.AdSdk
import com.lean.android.ad.core.ErrorCode
import com.lean.android.ad.repository.ReportHelper
import com.lean.android.ad.repository.ReportHelper.toCpmInt
import com.lean.android.ad.utils.AdLog
import com.lean.android.ad.utils.DisplayHelper
import java.util.UUID
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

@RestrictTo(RestrictTo.Scope.LIBRARY)
class FeedAdLoader(private val expectedWidth: Int) : AdLoader {

    companion object {
        private fun createFeedAdSlot(width: Int): AdSlot {
            return AdSlot.Builder().setCodeId(AdSdk.getAdConfig().adParamsProvider.getFeedAdId())
                .setExpressViewAcceptedSize(DisplayHelper.pxToDp(width).toFloat(), 0f) //dp
                .setImageAcceptedSize(width, 0) //单位px，高度0为自适应
                .setAdCount(1) // 请求广告数量为1到3条 （优先采用平台配置的数量）
                .setMediationAdSlot(
                    MediationAdSlot.Builder().setMuted(false).setVolume(1f).setBidNotify(true)
                        .build()
                ).build()
        }
    }

    override suspend fun load(activity: Activity): AdLoadState {
        val requestId = UUID.randomUUID().toString()
        AdLog.d(AdLog.AdFeedLoadTag, "FeedAd start to load , requestId $requestId")
        return suspendCoroutine { coroutine ->
            val nativeLoader = TTAdSdk.getAdManager().createAdNative(activity)
            nativeLoader.loadFeedAd(createFeedAdSlot(expectedWidth), object : FeedAdListener {
                override fun onError(code: Int, message: String?) {
                    AdLog.e(
                        AdLog.AdFeedLoadTag,
                        "FeedAd load failed, requestId $requestId, code $code, message $message"
                    )
                    ReportHelper.reportAdEvent(
                        requestId = requestId,
                        eventType = ReportHelper.AdEventType.AdError,
                        adPosition = ReportHelper.AdPositionType.Feed,
                        errorCode = code.toString()
                    )

                    coroutine.resume(AdLoadState.Error(ErrorCode.ErrorAdLoadFailed, message))
                }

                override fun onFeedAdLoad(ads: MutableList<TTFeedAd>?) {
                    val ad = ads?.firstOrNull()
                    if (ad == null) {
                        AdLog.e(
                            AdLog.AdFeedLoadTag, "FeedAd loaded, no ad found, requestId $requestId"
                        )
                        coroutine.resume(
                            AdLoadState.Error(
                                ErrorCode.ErrorAdLoadFailed, "ads is empty, no ad will display."
                            )
                        )
                    } else {
                        AdLog.d(
                            AdLog.AdFeedLoadTag, "FeedAd load success, requestId $requestId"
                        )

                        ad.mediationManager?.bestEcpm?.also { cpmInfo ->
                            val cpm = cpmInfo.ecpm.toCpmInt()
                            ReportHelper.reportAdEvent(
                                requestId = requestId,
                                eventType = ReportHelper.AdEventType.AdLoaded,
                                platformId = cpmInfo.sdkName.orEmpty(),
                                adPosition = ReportHelper.AdPositionType.Feed,
                                cpm = cpm
                            )
                        }

                        coroutine.resume(AdLoadState.Success(FeedAd(ad, requestId)))
                    }

                }
            })
        }
    }
}